<?php
include(APP_PATH.'/Lib/Action/AuthAction.class.php');

class PaperAction extends AuthAction {
    public function index(){
		$this->assign(array(
			'account' => $_SESSION['account'],
			'isLogin' => true
		));
		$this->display();
    }

    public function paper() {
        $tbl = new Model();
        $ret = $tbl->query('
            SELECT
                a.aid aid, a.uid uid, a.abstract abst,
                m.name name, m.university uni, m.email mail, 
                p.pid pid, p.filename fn, p.createtime ct
            FROM sfem_abstract a, sfem_member m, sfem_paper p
            WHERE a.uid = m.uid AND m.uid = p.uid
        ');
        
        $tReview = M('abst_review');
        $tSurvey = M('survey');
        foreach ($ret as $key=>$abst) {
            $review_ret = $tReview->field('ans')->where("aid={$abst['aid']}")->order('mtime DESC')->find();
            if ($review_ret) {
                $ret[$key]['review'] = $review_ret['ans']?'pass':'reject';
            } else {
                $ret[$key]['review'] = 'wait';
            }
            $survey_ret = $tSurvey->field('ans')->where("uid={$abst['uid']} AND sno=1")->order('mtime DESC')->find();
            if ($survey_ret) {
                $ret[$key]['survey'] = $survey_ret['ans']?'yes':'no';
            } else {
                $ret[$key]['survey'] = 'unknown';
            }
        }
        
        $this->assign('list', $ret);
        
        $this->assign(array(
            'account' => $_SESSION['account'],
            'isLogin' => true
        ));

        import('ORG.Util.String');
        $this->display();
    }
    
    public function abst() {
        
        $tbl = new Model();
        $ret = $tbl->query('
            SELECT m.uid id, m.name name, m.university uni, m.email mail, a.abstract abs, a.createtime ct, a.aid aid
            FROM sfem_member m, sfem_abstract a
            WHERE a.uid = m.uid
        ');

        $tReview = M('abst_review');
        foreach ($ret as $key=>$abst) {
            $review_ret = $tReview->field('ans')->where("aid={$abst['aid']}")->order('mtime DESC')->find();
            if ($review_ret) {
                $ret[$key]['review'] = $review_ret['ans']?'pass':'reject';
            } else {
                $ret[$key]['review'] = 'wait';
            }
        }
        
        $this->assign('list', $ret);
        
        import('ORG.Util.String');
        $this->assign(array(
            'account' => $_SESSION['account'],
            'isLogin' => true
        ));
        $this->display();
        
    }
    
    public function viewabs() {
        
        if(isset($_GET['id'])) {
            $aid = intval($_GET['id']);
            
            $tblAbstract = M('abstract');
            $abst = $tblAbstract->where("aid={$aid}")->find();
            
            if (!empty($abst)) {
                
                $tblMember = M('member');
                $memb = $tblMember->where("uid={$abst['uid']}")->find();
                
                $this->assign('abs', $abst);
                $this->assign('mem', $memb);
                
                $this->display();
            }
            
        }        
        
    }

    public function abstdownall () {

        $tbl = new Model();
        $ret = $tbl->query('
            SELECT m.uid id, m.name name, m.university uni, m.email mail, a.abstract abs, a.createtime ct
            FROM sfem_member m, sfem_abstract a
            WHERE a.uid = m.uid
        ');

        $filename = time();
        $filepath = "./Tmp/{$filename}.docx";

        require_once './PHPWord/PHPWord.php';

        // New Word Document
        $PHPWord = new PHPWord();

        // New portrait section
        $section = $PHPWord->createSection();

        // Add text elements
        $PHPWord->setDefaultFontSize(12);
        $PHPWord->addFontStyle('s1', array('bold'=>true, 'italic'=>false, 'size'=>16));
        $PHPWord->addFontStyle('s2', array('bold'=>false, 'italic'=>false, 'size'=>14));

        foreach ($ret as $abst) {
            $section->addText("姓名\t:\t{$abst['name']}\t\t（{$abst['id']}）", 's1');
            $ct = date('Y-m-d H:i', $abst['ct']);
            $section->addText("学校\t:\t{$abst['uni']}", 's2');
            $section->addText("Email\t:\t{$abst['mail']}", 's2');
            $section->addText("提交\t:\t{$ct}", 's2');
            $section->addTextBreak(2);
            $ps = explode("\n", $abst['abs']);
            foreach ($ps as $p) {
                $section->addText($p);
                $section->addTextBreak(1);
            }
            $section->addPageBreak();
        }

        $footer = $section->createFooter();
        $footer->addPreserveText('Page {PAGE}');

        // Save File
        $objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
        $objWriter->save($filepath);


        $file = fopen ( $filepath, "r" );
        $filelen = filesize($filepath);
        //输入文件标签   
        Header ( "Content-type: application/octet-stream" );  
        Header ( "Accept-Ranges: bytes" );  
        Header ( "Accept-Length: {$filelen}");
        Header ( "Content-Disposition: attachment; filename={$filename}.docx" );  
        //输出文件内容   
        //读取文件内容并直接输出到浏览器  
        echo fread ( $file, $filelen);  
        fclose ( $file );

        unlink($filepath);
    }

    public function abstdown () {

        $aid = intval($_GET['id']);

        $tbl = new Model();
        $ret = $tbl->query("
                SELECT m.uid id, m.name name, m.university uni, m.email mail, a.abstract abs, a.createtime ct, a.aid aid
                FROM sfem_member m, sfem_abstract a
                WHERE  aid = {$aid} AND a.uid = m.uid
        ");

        if (empty($ret)) {
            $this->error('发生错误！');
            exit;
        }

        $abst = $ret[0];

        $filename = "{$abst['aid']}_{$abst['name']}_{$abst['uni']}";
        $filepath = "./Tmp/{$filename}.docx";

        require_once './PHPWord/PHPWord.php';

        // New Word Document
        $PHPWord = new PHPWord();

        // New portrait section
        $section = $PHPWord->createSection();

        // Add text elements
        $PHPWord->setDefaultFontSize(12);
        $PHPWord->addFontStyle('s1', array('bold'=>true, 'italic'=>false, 'size'=>16));
        $PHPWord->addFontStyle('s2', array('bold'=>false, 'italic'=>false, 'size'=>14));

        $section->addText("姓名\t:\t{$abst['name']}\t\t（{$abst['id']}）", 's1');
        $ct = date('Y-m-d H:i', $abst['ct']);
        $section->addText("学校\t:\t{$abst['uni']}", 's2');
        $section->addText("Email\t:\t{$abst['mail']}", 's2');
        $section->addText("提交\t:\t{$ct}", 's2');
        $section->addTextBreak(2);
        $ps = explode("\n", $abst['abs']);
        foreach ($ps as $p) {
            $section->addText($p);
            $section->addTextBreak(1);
        }

        $footer = $section->createFooter();
        $footer->addPreserveText('Page {PAGE}');

        // Save File
        $objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
        $objWriter->save($filepath);


        $file = fopen ( $filepath, "r" );
        $filelen = filesize($filepath);
        //输入文件标签   
        Header ( "Content-type: application/octet-stream" );  
        Header ( "Accept-Ranges: bytes" );  
        Header ( "Accept-Length: {$filelen}");
        Header ( "Content-Disposition: attachment; filename={$filename}.docx" );  
        //输出文件内容   
        //读取文件内容并直接输出到浏览器  
        echo fread ( $file, $filelen);  
        fclose ( $file );

        unlink($filepath);
    }

    //下载论文文件
    public function paperdown () {

        $pid = intval($_GET['id']);

        $tbl = new Model();
        $ret = $tbl->query("
            SELECT m.uid uid, m.name name, p.filename fn, p.savename sn
            FROM sfem_member m, sfem_paper p
            WHERE m.uid = p.uid AND p.pid = {$pid}
        ");

        if (empty($ret)) {
            $this->error('发生错误！');
            exit;
        }

        $pfile = $ret[0];

        $filename = "{$pfile['uid']}_{$pfile['name']}_{$pfile['fn']}";
        $filepath = "./Uploads/doc/{$pfile['sn']}";

        $file = fopen ( $filepath, "r" );
        $filelen = filesize($filepath);
        //输入文件标签   
        Header ( "Content-type: application/octet-stream" );  
        Header ( "Accept-Ranges: bytes" );  
        Header ( "Accept-Length: {$filelen}");
        Header ( "Content-Disposition: attachment; filename={$filename}" );  
        //输出文件内容   
        //读取文件内容并直接输出到浏览器  
        echo fread ( $file, $filelen);  
        fclose ( $file );
    }

    //下载全部论文文件
    public function paperdownall () {
        $doc_dir = './Uploads/doc/';
        $base_dir = './Tmp/';
        $folder_name = time();

        //建立临时文件夹
        $folder_path = $base_dir . $folder_name . '/';
        if (!is_dir($folder_path)) {
            mkdir($folder_path);
        }

        //读取文件列表
        $tbl = new Model();
        $ret = $tbl->query("
            SELECT m.uid uid, m.name name, m.university uni, p.filename fn, p.savename sn
            FROM sfem_member m, sfem_paper p
            WHERE m.uid = p.uid
        ");
        if (empty($ret)) {
            $this->error('发生错误！');
            exit;
        }

        //复制文件&改名
        // echo '<h1>处理中…</h1><ul>';
        foreach ($ret as $file) {
            $from_path = $doc_dir . $file['sn'];
            $to_path = "{$folder_path}/{$file['uid']}_{$file['name']}_{$file['uni']}_{$file['fn']}";
            if (file_exists($from_path)) {
                // echo '<li>';
                // echo copy($from_path, $to_path)? '√':'X';
                // echo "\t{$file['uid']}_{$file['name']}_{$file['fn']}";
                // echo '</li>';
                copy($from_path, $to_path);
            }
        }
        // echo '</ul><p>开始下载…</p>';

        //创建压缩包
        $zip_path = $base_dir . $folder_name . '.zip';
        require_once './pclzip/pclzip.lib.php';
        $archive = new PclZip($zip_path);
        $archive->add($folder_path);

        //删除临时目录
        $this->deldir($folder_path);

        $file = fopen ($zip_path, 'r');
        $filelen = filesize($zip_path);
        //输入文件标签   
        Header ( "Content-type: application/octet-stream" );  
        Header ( "Accept-Ranges: bytes" );  
        Header ( "Accept-Length: {$filelen}");
        Header ( "Content-Disposition: attachment; filename='ISPR_全部论文_{$folder_name}.zip'" );
        //输出文件内容   
        //读取文件内容并直接输出到浏览器  
        echo fread ( $file, $filelen);  
        fclose ( $file );

        //删除压缩包
        unlink($zip_path);
    }

    private function deldir($dir) {
        //先删除目录下的文件：
        $dh=opendir($dir);
        while ($file=readdir($dh)) {
            if($file!="." && $file!="..") {
                $fullpath=$dir."/".$file;
                if(!is_dir($fullpath)) {
                    unlink($fullpath);
                } else {
                    deldir($fullpath);
                }
            }
        }
        closedir($dh);

        //删除当前文件夹：
        return rmdir($dir);
    }
    
}